package cn.tedu.test;

import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;

import java.sql.*;
import java.util.Scanner;

public class test2 {
    public static void main(String[] args) throws Exception {
       // method();
        method3();
    }

    private static void method() throws Exception {
        //1.注册成功
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取
        String url = "jdbc:myql://localhost:3306/cgb2015?characterEncoding=utf8";
        Connection conn = DriverManager.getConnection(url, "root", "root");
        //3.获取传输器
        Statement st = conn.createStatement();
        //4.执行sql
        String sql = "select*from user where name=?and password=?";
        ResultSet rs = st.executeQuery(sql);

        //5.解析结果集
        if (rs.next()) {
            System.out.println("登陆成功");
        } else {
            System.out.println("登陆失败");
        }
        //6.释放资源
        rs.close();//释放
        st.close();//释放
        conn.close();//释放
    }

    private static void method2() throws Exception {
        System.out.println("开始程序");

        //1.注册成功
        Class.forName("com.mysql.jdbc.Driver");
        //2.获取
        String url = "jdbc:myql://localhost:3306/cgb2015?characterEncoding=utf8";
        Connection conn = DriverManager.getConnection(url, "root", "root");
        //3.获取传输器
        Statement st = conn.createStatement();
        //4.执行sql
        String a = new Scanner(System.in).nextLine();//用户名
        String b = new Scanner(System.in).nextLine();//密码
        String sql = "select*from user where name='" + a + "'and password='" + b + "'";
        ResultSet rs = st.executeQuery(sql);

        //5.解析结果集
        if (rs.next()) {
            System.out.println("登陆成功");
        } else {
            System.out.println("登陆失败");
        }
        //6.释放资源
        rs.close();//释放
        st.close();//释放
        conn.close();//释放
    }

    private static void method3() throws Exception {

        //1.注册成功
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取
        String url = "jdbc:mysql://localhost:3306/cgb2015?characterEncoding=utf8";
        Connection conn = DriverManager.getConnection(url, "root", "root");
        //3.获取传输器
        /*Statement st=conn.createStatement();*/

        String a = new Scanner(System.in).nextLine();//用户名
        String b = new Scanner(System.in).nextLine();//密码
        //sql骨架，？占位符
        String sql = "select *from user where name=?and password=?";
        //PreparedStatement把sql骨架和参数分开发送给数据的
        PreparedStatement ps = conn.prepareStatement(sql);
        //给sql设置参数---指定给那个问好赋值
        ps.setString(1, a);
        ps.setString(2, b);
        //4.执行sql
        ResultSet rs = ps.executeQuery();

        //5.解析结果集
        if (rs.next()) {
            System.out.println("登陆成功");
        } else {
            System.out.println("登陆失败");
        }
        //6.释放资源
        rs.close();//释放
        ps.close();//释放
        conn.close();//释放
    }

}
//自我复习
